package top.carrotguo.weibo.adapter;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;

import top.carrotguo.weibo.R;
import top.carrotguo.weibo.bean.HomeTimeLine;
import top.carrotguo.weibo.ui.base.BaseActivity;
import top.carrotguo.weibo.ui.base.ImageActivity;
import top.carrotguo.weibo.utils.UIUtils;

public class StatusGridImgsAdapter extends BaseAdapter {

    private ArrayList<HomeTimeLine.UsersBean.Pic> datas;
    private Context mContext;

    public StatusGridImgsAdapter(Context context, ArrayList<HomeTimeLine.UsersBean.Pic> datas){
        mContext = context;
        this.datas = datas;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public String getItem(int position) {
        return datas.get(position).getNormal_pic();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = View.inflate(UIUtils.getContext(), R.layout.item_image,null);
            holder = new ViewHolder();
            holder.ivPic = convertView.findViewById(R.id.iv_pic);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //根据父控件大小计算图片大小
        GridView gridView = (GridView) parent;
        int columnCount = gridView.getNumColumns();
        int itemWidth = (gridView.getWidth()-gridView.getHorizontalSpacing()*(columnCount-1)
                - gridView.getPaddingLeft() - gridView.getPaddingRight())/columnCount;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(itemWidth,itemWidth);
        holder.ivPic.setLayoutParams(params);
        //Logger.e("width:"+itemWidth);我也不明白为什么有时候加载不全
        Glide.with(mContext).load(getItem(position)).into(holder.ivPic);

        //图片的点击事件
        holder.ivPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(ImageActivity.IMAGES,datas);
                bundle.putInt(ImageActivity.CUR_INDEX,position);
                ((BaseActivity)mContext).readyGo(ImageActivity.class,bundle);
            }
        });

        return convertView;
    }

    class ViewHolder{
        ImageView ivPic;
    }
}
